package com.sercomm.ott.mediaplayer;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.sercomm.ott.mediaplayer.custom_view.ColorTrackView;
import com.sercomm.ott.mediaplayer.custom_view.MyListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import static com.sercomm.ott.mediaplayer.R.id.progressBar;

/**
 * Created by ott on 7/26/17.
 */

public class SimpleActivity extends Activity implements View.OnClickListener{
    private static final String TAG = "SimpleActivity";
    private static final String[] INFO_LIST = new String[]{"name", "detail"};
    private static final int[] INFO_LIST_RES = new int[]{R.id.info_name, R.id.info_detail};
    private MyListView info_list = null;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    //simple swipe refresh view
    private List<String> mList;
    private StringAdapter mAdapter;
    private SimpleSwipeRefreshView mSwipeRefreshView;

    private Button mButton_request;
    private TextView responseText;
    private Button mButton_post;

    private Button mButton_image;
    private ImageView mImageView;
    private ImageView mImageView2;
    private ProgressDialog progressDialog;
    private final String[] IMAGE_PATH =
            {   "http://172.21.10.45/1.png",
                "http://172.21.10.45/2.png",
                "http://172.21.10.45/3.png"
            };

    private WebView webView;

    private ColorTrackView colorTrackView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.simple);
        info_list = (MyListView) findViewById(R.id.info_list);

        if(getIntent().getBooleanExtra("simple_flag",false)){

        }


        final ArrayList<HashMap<String, String>> items = getInfo();
        final SimpleAdapter adapter = new SimpleAdapter(this, items, R.layout.list_res, INFO_LIST, INFO_LIST_RES);
        info_list.setAdapter(adapter);

        info_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                HashMap<String, String> map = items.get(i);
                Toast.makeText(SimpleActivity.this, map.get("name") + map.get("detail"), Toast.LENGTH_LONG).show();
            }
        });
        info_list.setDelButtionClickListener(new MyListView.DelButtonClickListener() {
            @Override
            public void clickHappened(int position) {
                items.remove(position);
                adapter.notifyDataSetChanged();
            }
        });


        mSwipeRefreshView = (SimpleSwipeRefreshView) findViewById(R.id.sswv);
        ListView sswv_list = (ListView)findViewById(R.id.sswv_list);
        mList = new ArrayList<>();
        mAdapter = new StringAdapter();
        sswv_list.setAdapter(mAdapter);
        mSwipeRefreshView.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mSwipeRefreshView.setColorSchemeResources(R.color.colorAccent,
                android.R.color.holo_blue_bright, R.color.colorPrimaryDark,
                android.R.color.holo_orange_dark, android.R.color.holo_red_dark, android.R.color.holo_purple);
        mSwipeRefreshView.setItemCount(10);
        mSwipeRefreshView.measure(0,0);
        mSwipeRefreshView.setRefreshing(true);
        initEvent();
        initData();
        sswv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(SimpleActivity.this,"click "+ i +mList.get(i),Toast.LENGTH_SHORT).show();
            }
        });

        mButton_request = (Button)findViewById(R.id.send_request);
        mButton_request.setOnClickListener(this);
        responseText = (TextView)findViewById(R.id.response);

        mButton_post = (Button)findViewById(R.id.post_test);
        mButton_post.setOnClickListener(this);

        AssetManager assetManager =getAssets();
        try{
            StringBuilder builder=new StringBuilder();
            for(String asset : assetManager.list("")){
                if(asset.endsWith("json")){
                    Log.d(TAG,"----find "+asset);
                    InputStream inputStream = assetManager.open(asset);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    String line;
                    while ((line=reader.readLine())!=null){
                        builder.append(line);
                    }
                }
            }
            parseJson(builder.toString());
        }catch (Exception e){
            Toast.makeText(this,"failed to load",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

        mButton_image = (Button)findViewById(R.id.image_button);
        mButton_image.setOnClickListener(this);
        mImageView = (ImageView)findViewById(R.id.image_view);
        mImageView2 = (ImageView)findViewById(R.id.image_view2);
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("tip");
        progressDialog.setMessage("loading.....");
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);


        webView =(WebView)findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String url){
                view.loadUrl(url);
                return true;
            }
        });
        webView.loadUrl("http://www.baidu.com");

        colorTrackView = (ColorTrackView)findViewById(R.id.id_changeTextColorView);

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    public void startLeftChange(View view)
    {
        colorTrackView.setDirection(0);
        ObjectAnimator.ofFloat(colorTrackView, "progress", 0, 1).setDuration(2000)
                .start();
    }

    public void startRightChange(View view)
    {
        colorTrackView.setDirection(1);
        ObjectAnimator.ofFloat(colorTrackView, "progress", 0, 1).setDuration(2000)
                .start();
    }

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.send_request:
                Log.d(TAG,"----onclik send Request httpclinet");
                sendRequestWithHttpClient();
                break;
            case R.id.post_test:
                postWithHttpClient();
                break;
            case R.id.image_button:
                //new MyAsyncTask().execute(IMAGE_PATH);
                new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,IMAGE_PATH[0],"0");
                new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,IMAGE_PATH[1],"1");
                break;
        }
    }
    public class MyAsyncTask extends AsyncTask<String, Integer, byte[]>{
        String item = "";
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            //showProgressBar();
            progressDialog.show();
        }
        @Override
        protected byte[] doInBackground(String...params){
            //Bitmap bitmap= getImageBitmap(params[0]);
            URL imgUrl;
            Bitmap bitmap = null;
            byte[] image = new byte[]{};
            try {
                item = params[1];
                imgUrl = new URL(params[0]);
                HttpURLConnection conn = (HttpURLConnection)imgUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                //InputStream is = conn.getInputStream();
                InputStream is = (InputStream)conn.getContent();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] data = new byte[1024];
                int length = 0;
                long total_length = 0;
                long file_length = conn.getContentLength();
                Log.d(TAG,"----file_length "+file_length);
                while(-1 != (length=is.read(data))){
                    total_length += length;
                    byteArrayOutputStream.write(data,0,length);
                    float progress = ((float)total_length/(float)file_length) * 100;
                    Log.d(TAG,"=====progress "+progress+" total_length "+total_length);
                    publishProgress((int)progress);
                }
                //bitmap = BitmapFactory.decodeStream(is);
                image = byteArrayOutputStream.toByteArray();
                is.close();
                byteArrayOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return image;
            //return bitmap;
        }
        @Override
        protected void onProgressUpdate(Integer...values){
            super.onProgressUpdate(values);
            progressDialog.setProgress(values[0]);
        }
        @Override
        protected void onPostExecute(byte[] result){
            super.onPostExecute(result);
            Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
            if(item.equals("0")){
                mImageView.setImageBitmap(bitmap);
            }else if (item.equals("1")){
                mImageView2.setImageBitmap(bitmap);
            }
            progressDialog.dismiss();
            //dismissProgressBar();
        }
    }
    /*
    private Bitmap getImageBitmap(String url){
        URL imgUrl;
        Bitmap bitmap = null;
        try {
            imgUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imgUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }*/
    ProgressBar progressBar =null;
    ViewGroup viewGroup = null;
    /**
     * 在母布局中间显示进度条
     */
    private void showProgressBar(){
        progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleLarge);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //params.addRule(RelativeLayout.CENTER_IN_PARENT,  RelativeLayout.TRUE);
        progressBar.setVisibility(View.VISIBLE);
        Context context = getApplicationContext();
        viewGroup = (ViewGroup)findViewById(R.id.parent_view);
        //      MainActivity.this.addContentView(progressBar, params);
        viewGroup.addView(progressBar, params);
    }
    /**
     * 隐藏进度条
     */
    private void dismissProgressBar(){
        if(progressBar != null){
            progressBar.setVisibility(View.GONE);
            viewGroup.removeView(progressBar);
            progressBar = null;
        }
    }
    public static final int SHOW_RESPONSE = 0x000;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            switch (msg.what){
                case SHOW_RESPONSE:
                    String response = (String)msg.obj;
                    responseText.setText(response);
            }
        }
    };
    public void sendRequestWithHttpClient(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try{
                    //URL url = new URL("http://10.0.2.2/get_data.json");
                    URL url = new URL("http://192.168.1.64:8080/get_data.json");
                    //URL url = new URL("http://www.baidu.com");
                    connection= (HttpURLConnection)url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    if(connection.getResponseCode() == 200){
                        InputStream in = connection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine())!=null){
                            response.append(line);
                        }
                        parseJson(response.toString());
                        Message message = new Message();
                        message.what = SHOW_RESPONSE;
                        message.obj = response.toString();
                        handler.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(connection!=null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
    public void postWithHttpClient(){
        return;
    }
    private void parseJson(String jsonData){
        try{
            JSONArray jsonArray = new JSONArray(jsonData);
            for(int i =0 ;i<jsonArray.length();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String name1 = jsonObject.getString("name");
                JSONArray array = jsonObject.getJSONArray("sample");
                Log.d(TAG,"-----name1 is "+name1);
                parseJson2(array.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void parseJson2(String jsonData){
        try{
            JSONArray jsonArray = new JSONArray(jsonData);
            for (int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String name2 = jsonObject.getString("name");
                String uri = jsonObject.getString("uri");
                Log.d(TAG,"-----name2 is "+ name2);
                Log.d(TAG,"------uri is "+ uri);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    private ArrayList<HashMap<String, String>> getInfo() {
        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        HashMap<String, String> item = null;
        item = new HashMap<>();
        item.put(INFO_LIST[0], "11111");
        item.put(INFO_LIST[1], "22222");
        list.add(item);
        item = new HashMap<>();
        item.put(INFO_LIST[0], "2222");
        item.put(INFO_LIST[1], "333333");
        list.add(item);
        SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);
        item = new HashMap<>();
        item.put(INFO_LIST[0],"name");
        item.put(INFO_LIST[1], pref.getString("name","ok"));
        list.add(item);

        return list;
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Simple Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }


    private void initEvent(){
        mSwipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });
        mSwipeRefreshView.setOnLoadMoreListener(new SimpleSwipeRefreshView.onLoadMoreListener(){
            @Override
            public void onLoadMore(){
                loadMoreData();
            }
        });

    }
    private void initData(){
        /*
        mList.clear();
        mList.addAll(DataResource.getData());
        mAdapter.notifyDataSetChanged();
        if(mSwipeRefreshView.isRefreshing()) {
            mSwipeRefreshView.setRefreshing(false);
        }
        */
        //模仿加载延迟
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mList.clear();
                mList.addAll(DataResource.getData());
                mAdapter.notifyDataSetChanged();
                if(mSwipeRefreshView.isRefreshing()) {
                    mSwipeRefreshView.setRefreshing(false);
                }

            }
        },2000);
    }
    private void loadMoreData(){
        /*
        mList.clear();
        mList.addAll(DataResource.getMoreData());
        mAdapter.notifyDataSetChanged();
        mSwipeRefreshView.setLoading(false);
        */
        //模仿加载延迟
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mList.clear();
                mList.addAll(DataResource.getMoreData());
                mAdapter.notifyDataSetChanged();
                mSwipeRefreshView.setLoading(false);
            }
        },2000);
    }
    public static class DataResource {
        private static List<String> datas = new ArrayList<>();
        private static int page = 0;

        public static List<String> getData() {
            page = 0;
            datas.clear();
            for (int i = 0; i < 3; i++) {
                datas.add("item " + i);
            }
            return datas;
        }

        public static List<String> getMoreData() {
            page = page + 1;
            for (int i = 3 * page; i < 3 * (page + 1); i++) {
                datas.add("item " + i);
            }

            return datas;
        }
    }
    /**
     * 适配器
     */
    private class StringAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(SimpleActivity.this, android.R.layout.simple_list_item_1, null);
            }

            TextView tv = (TextView) convertView;
            tv.setGravity(Gravity.CENTER);
            tv.setPadding(0, 20, 0, 20);
            tv.setText(mList.get(position));

            return convertView;
        }
    }
}
